from rest_framework import serializers
from .models import (
    AdminUser, Department, Role, Resource, RoleResource, Workflow,
    WorkflowPermission, Position, WorkflowApprovalNode, Task, AuditRecord
)
import json

class AdminUserSerializer(serializers.ModelSerializer):
    """管理员用户序列化器"""
    department_name = serializers.CharField(source='department.name', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True)
    
    class Meta:
        model = AdminUser
        fields = ['id', 'name', 'phone', 'role', 'role_name', 'department', 'department_name', 'created_at', 'last_login']
        read_only_fields = ['created_at', 'last_login']
        
class AdminLoginSerializer(serializers.Serializer):
    """管理员登录序列化器"""
    phone = serializers.CharField(required=False, help_text='手机号')
    password = serializers.CharField(required=False, help_text='密码')
    sms_code = serializers.CharField(required=False, help_text='短信验证码')
    login_type = serializers.ChoiceField(choices=['password', 'sms'], help_text='登录类型：password-密码登录，sms-短信验证码登录')
    
    def validate(self, attrs):
        login_type = attrs.get('login_type')
        phone = attrs.get('phone')
        
        if not phone:
            raise serializers.ValidationError("手机号不能为空")
            
        if login_type == 'password' and not attrs.get('password'):
            raise serializers.ValidationError("密码不能为空")
            
        if login_type == 'sms' and not attrs.get('sms_code'):
            raise serializers.ValidationError("短信验证码不能为空")
            
        return attrs

class DepartmentSerializer(serializers.ModelSerializer):
    """部门序列化器"""
    class Meta:
        model = Department
        fields = ['id', 'name']

class ResourceSerializer(serializers.ModelSerializer):
    """资源序列化器"""
    class Meta:
        model = Resource
        fields = ['id', 'name', 'pid', 'url']

class RoleSerializer(serializers.ModelSerializer):
    """角色序列化器"""
    class Meta:
        model = Role
        fields = ['id', 'name']

class PositionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Position
        fields = '__all__'

class WorkflowSerializer(serializers.ModelSerializer):
    params_dict = serializers.SerializerMethodField()
    
    class Meta:
        model = Workflow
        fields = '__all__'
    
    def get_params_dict(self, obj):
        try:
            return json.loads(obj.params)
        except:
            return {}
    
    def validate_params(self, value):
        try:
            json.loads(value)
            return value
        except json.JSONDecodeError:
            raise serializers.ValidationError("参数必须是有效的JSON格式")

class WorkflowPermissionSerializer(serializers.ModelSerializer):
    role_name = serializers.CharField(source='role_id.name', read_only=True)
    workflow_name = serializers.CharField(source='workflow_id.name', read_only=True)
    
    class Meta:
        model = WorkflowPermission
        fields = '__all__'

class WorkflowApprovalNodeSerializer(serializers.ModelSerializer):
    workflow_name = serializers.CharField(source='workflow_id.name', read_only=True)
    position_name = serializers.CharField(source='position_id.name', read_only=True)
    
    class Meta:
        model = WorkflowApprovalNode
        fields = '__all__'

class TaskSerializer(serializers.ModelSerializer):
    workflow_name = serializers.CharField(source='workflow_id.name', read_only=True)
    applicant_name = serializers.CharField(source='userid.name', read_only=True)
    next_approver_name = serializers.CharField(source='next_audit.name', read_only=True, allow_null=True)
    params_dict = serializers.SerializerMethodField()
    status_display = serializers.CharField(source='get_task_status_display', read_only=True)
    
    class Meta:
        model = Task
        fields = '__all__'
    
    def get_params_dict(self, obj):
        try:
            return json.loads(obj.params)
        except:
            return {}
    
    def validate_params(self, value):
        try:
            json.loads(value)
            return value
        except json.JSONDecodeError:
            raise serializers.ValidationError("参数必须是有效的JSON格式")

class AuditRecordSerializer(serializers.ModelSerializer):
    task_name = serializers.CharField(source='task_id.name', read_only=True)
    auditor_name = serializers.CharField(source='audit_user.name', read_only=True)
    status_display = serializers.CharField(source='get_audit_status_display', read_only=True)
    
    class Meta:
        model = AuditRecord
        fields = '__all__' 